package servlet;
import servlet.Connections;
import javax.servlet.*;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.http.*;

public class checkCredential extends HttpServlet 
 {
	
	Connections con=new Connections();
	Statement stmt=null;
	ResultSet rs=null;
	PrintWriter out;
	boolean foundflag=false;
	String authfailed="Authentication Failed.";
	
	String query,user_Type;
	
	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
		{
			
			
			String username,password;
			username=request.getParameter("user");
			password=request.getParameter("pwd");
			
			out=response.getWriter();
			out.println(username);
			out.println(password);
		
			try
			{							
				
				stmt=con.getConnection().createStatement();
				query="select * from login where username='"+username+"'";
				rs=stmt.executeQuery(query);
						
			  
				while(rs.next())
				{
					if (username.equals(rs.getString(1))&& password.equals(rs.getString(2)))
					{		foundflag=true;
							user_Type=rs.getString(3);
								break;
					}
					else
					{
						foundflag=false;
					}
				}	
				if (foundflag==true)
				{
					if(user_Type.equals("Administrator"))
					{
						response.sendRedirect("Administrator.jsp?username="+username);
					}
					else if(user_Type.equals("User"))
							{
								response.sendRedirect("SubUser.jsp?username="+username);
							}
					//out.println("Correct");
				}
				else
					{
						
						String message="Authentication Failed either username or passowrd is incoorect";
						request.getSession().setAttribute("message",message);
						response.sendRedirect("Login.jsp");
						//HttpSession sess=request.getSession();
						//sess.setAttribute("retval","fail");
						//response.sendRedirect("Login.jsp?authFailed="+authfailed);
						//out.println("Incorrect");
					}

			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		
			
		}
	
 }
	
	
	
	
	